# BSD3.0
# cili@163.com

import tkinter as tk
from tkinter.ttk import Entry, Button


class EncodingDecoderHelper:
    def __init__(self, root):
        btn_names = ["十进制转二进制", "二进制转十进制", "字符转十进制数", "十进制数转字符"]
        self.inputs = [tk.StringVar(), tk.StringVar(), tk.StringVar(), tk.StringVar()]
        self.outputs = [tk.StringVar(), tk.StringVar(), tk.StringVar(), tk.StringVar()]

        self.root = root
        self.root.title("编码解码辅助工具")

        entrys = [Entry(self.root, textvariable=item, width=24) for item in self.inputs]
        [entry.grid(row=index, column=0, padx=5, pady=5) for index, entry in enumerate(entrys)]
        [entry.bind('<KeyRelease>', lambda event, index=index: self.check_length(event, index))
         for index, entry in enumerate(entrys)]

        [Button(self.root, text=bval, command=lambda index=index: self.command(index), width=16)
         .grid(row=index, column=1, padx=5, pady=10) for index, bval in enumerate(btn_names)]

        out_entrys = [Entry(self.root, textvariable=item, width=24) for item in self.outputs]
        [entry.grid(row=index, column=2, padx=5, pady=5) for index, entry in enumerate(out_entrys)]
        [entry.state(['readonly']) for index, entry in enumerate(out_entrys)]

        self.root.resizable(False, False)
        self.center_windows()

    def check_length(self, event, index):
        input_str = self.inputs[index].get().replace(' ', '')
        input_length_limits = [6, 17, 1, 6]
        if len(input_str) > input_length_limits[index]:
            self.inputs[index].set(input_str[:-1])

    def command(self, index):
        in_str = self.inputs[index].get().replace(' ', '')
        funs = [lambda x: bin(int(x))[2:], lambda x: str(int(x, 2)),
                lambda x: str(int.from_bytes(in_str.encode('gbk'), byteorder='big')),
                lambda x: int(in_str).to_bytes((int(in_str).bit_length() + 7) // 8, byteorder='big').decode('gbk')]
        try:
            self.outputs[index].set(funs[index](in_str))
        except ValueError:
            self.outputs[index].set('无法进行转换该数！')


    def center_windows(self):
        self.root.update()
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = self.root.winfo_width()
        window_height = self.root.winfo_height()
        x = int((screen_width / 2) - (window_width / 2))
        y = int((screen_height / 2) - (window_height / 2))
        self.root.geometry(f"+{x}+{y}")


if __name__ == "__main__":
    root = tk.Tk()
    app = EncodingDecoderHelper(root)
    root.mainloop()
